import { useState, useEffect, useContext } from 'react'
import { Layout, Menu, Button } from 'antd'
import { MenuFoldOutlined, MenuUnfoldOutlined, PushpinOutlined, PushpinFilled, DownOutlined, HomeOutlined, UpOutlined, CloseOutlined } from '@ant-design/icons'
import { AiOutlineTool, AiOutlineHome, AiOutlineDatabase, AiOutlineCluster, AiOutlineCodeSandbox } from 'react-icons/ai'
import { BsDatabaseFillGear, BsTools, BsBoxSeam, BsFileEarmarkCode } from 'react-icons/bs'
import { MdStorage, MdOutlineFactory } from 'react-icons/md'
import { FiSettings } from 'react-icons/fi'
import './App.css'
import Dashboard from './components/Dashboard'
import MermaidDiagram from './components/MermaidDiagram'
import ProductLibrary from './components/ProductLibrary'
import ResourceLibrary from './components/ResourceLibrary'
import ProcessTemplateLibrary from './components/ProcessTemplateLibrary'
import ProductBOM, { BOMDetail } from './components/ProductBOM'
import ProductProcess from './components/ProductProcess'
import ProductBOP, { BOPDetail } from './components/ProductBOP'
import ProcessDetail from './components/ProcessDetail'
import ProductDetail from './components/ProductDetail'
import ProcessTemplateDetail from './components/ProcessTemplateDetail'
import IntelligentRecommendation from './components/IntelligentRecommendation'
import DataVersion from './components/DataVersion'
import SampleData from './components/SampleData'

import { SYSTEM_NAME } from './config'
import { TabsProvider, TabsContext } from './contexts/TabsContext'

const { Header, Sider, Content, Footer } = Layout

// 路由内容组件
const AppContent = () => {
  const { activeTab, tabs, tabContents, addTab, changeTab, closeTab } = useContext(TabsContext);
  const [collapsed, setCollapsed] = useState(false);
  const [pinned, setPinned] = useState(true);
  const [subMenuOpen, setSubMenuOpen] = useState(false);
  const [manufacturingSubMenuOpen, setManufacturingSubMenuOpen] = useState(false);
  const [systemSettingsSubMenuOpen, setSystemSettingsSubMenuOpen] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    // 设置页面满屏
    const handleResize = () => {
      document.documentElement.style.height = `${window.innerHeight}px`;
      // 检测是否为移动设备
      setIsMobile(window.innerWidth <= 576);
      
      // 如果是手机端，自动折叠侧边栏
      if (window.innerWidth <= 576) {
        setCollapsed(true);
        setPinned(false);
      }
    };
    
    handleResize();
    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [])

  // 处理折叠按钮点击
  const handleCollapseClick = () => {
    // 如果是移动设备，则控制移动菜单的开关
    if (isMobile) {
      setIsMobileMenuOpen(!isMobileMenuOpen);
      return;
    }
    
    // 如果已锁定，则不允许折叠
    if (!pinned) {
      setCollapsed(!collapsed);
      // 如果折叠菜单，则取消锁定状态和关闭子菜单
      if (!collapsed) {
        setPinned(false);
        setSubMenuOpen(false);
        setManufacturingSubMenuOpen(false);
        setSystemSettingsSubMenuOpen(false);
      }
    }
  };

  // 处理锁定按钮点击
  const handlePinClick = () => {
    // 移动设备不显示锁定按钮
    if (isMobile) return;
    
    setPinned(!pinned);
    // 如果锁定，则展开菜单
    if (!pinned && collapsed) {
      setCollapsed(false);
    }
  };

  // 处理子菜单展开/折叠
  const toggleSubMenu = (e) => {
    e.stopPropagation(); // 阻止事件冒泡
    setSubMenuOpen(!subMenuOpen);
  };
  
  // 处理制造工艺规划子菜单展开/折叠
  const toggleManufacturingSubMenu = (e) => {
    e.stopPropagation(); // 阻止事件冒泡
    setManufacturingSubMenuOpen(!manufacturingSubMenuOpen);
  };

  // 处理系统设置子菜单展开/折叠
  const toggleSystemSettingsSubMenu = (e) => {
    e.stopPropagation(); // 阻止事件冒泡
    setSystemSettingsSubMenuOpen(!systemSettingsSubMenuOpen);
  };

  // 渲染标签页内容
  const renderTabContent = (tabKey) => {
    // 处理特殊内置标签页
    switch (tabKey) {
      case 'home':
        return <Dashboard />;
      case 'productLibrary':
        return <ProductLibrary />;
      case 'resourceLibrary':
        return <ResourceLibrary />;
      case 'processTemplateLibrary':
        return <ProcessTemplateLibrary />;
      case 'productBOM':
        return <ProductBOM />;
      case 'productProcess':
        return <ProductProcess />;
      case 'productBOP':
        return <ProductBOP />;
      case 'dataVersion':
        return <DataVersion />;
      case 'sampleData':
        return <SampleData />;
      default:
        // 处理动态创建的标签页
        const content = tabContents[tabKey];
        if (content) {
          switch (content.componentType) {
            case 'ProcessDetail':
              return <ProcessDetail routeId={content.props.routeId} code={content.props.code} />;
            case 'BOMDetail':
              return <BOMDetail bomId={content.props.bomId} code={content.props.code} />;
            case 'BOPDetail':
              return <BOPDetail bopId={content.props.bopId} code={content.props.code} />;
            case 'ProductDetail':
              return <ProductDetail productId={content.props.productId} />;
            case 'ProcessTemplateDetail':
              return <ProcessTemplateDetail templateId={content.props.templateId} />;
            case 'IntelligentRecommendation':
              return <IntelligentRecommendation 
                productId={content.props.productId} 
                bomId={content.props.bomId}
                productCode={content.props.productCode}
                productName={content.props.productName}
                initialActiveTab={content.props.initialActiveTab}
              />;
            default:
              return <div>未知的组件类型</div>;
          }
        }
        return <div>标签页内容未定义</div>;
    }
  };

  return (
    <div className="system-root">
      <Layout className="layout-root">
        <Header className={`layout-header ${isMobile ? 'mobile-header' : ''}`}>
          <div className="header-left">
            {/* 移动端专用菜单按钮 */}
            {isMobile && (
              <Button
                type="text"
                icon={isMobileMenuOpen ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}
                onClick={handleCollapseClick}
                className="mobile-menu-button"
                style={{ color: '#fff', fontSize: '18px', marginRight: '8px' }}
              />
            )}
            <img src="/logo.png" alt="系统logo" className="header-logo" />
            <span className={`header-title ${isMobile ? 'mobile-title' : ''}`}>{SYSTEM_NAME}</span>
            <div className={`header-tabs ${isMobile ? 'mobile-tabs' : ''}`}>
              <div
                className={`header-tab ${activeTab === 'home' ? 'active' : ''}`}
                onClick={() => changeTab('home')}
              >
                <AiOutlineHome className="header-tab-icon" />
                <span>首页</span>
              </div>
              {tabs.filter(tab => tab.key !== 'home').map(tab => (
                <div 
                  key={tab.key} 
                  className={`header-tab ${activeTab === tab.key ? 'active' : ''}`}
                  onClick={() => changeTab(tab.key)}
                >
                  <span className="tab-title">{tab.title}</span>
                  {tab.closable && (
                    <CloseOutlined
                      className="tab-close-icon"
                      onClick={(e) => {
                        e.stopPropagation();
                        closeTab(tab.key);
                      }}
                    />
                  )}
                </div>
              ))}
            </div>
          </div>
        </Header>
        
        <div className="layout-main">
          <div className={`layout-sider ${collapsed ? 'collapsed' : ''} ${isMobileMenuOpen && isMobile ? 'mobile-menu-open' : ''}`}>
            <div className="sider-menu">
              <div 
                className={`sider-menu-item ${subMenuOpen ? 'active' : ''}`}
                onClick={() => (!collapsed || isMobile) && setSubMenuOpen(!subMenuOpen)}
              >
                <span className="sider-menu-icon">
                  <AiOutlineDatabase />
                </span>
                <span className="sider-menu-label">库管理</span>
                {(!collapsed || isMobile && isMobileMenuOpen) && (
                  <span className="sider-menu-caret" onClick={toggleSubMenu}>
                    {subMenuOpen ? <UpOutlined /> : <DownOutlined />}
                  </span>
                )}
              </div>

              {/* 子菜单项 */}
              {(!collapsed || (isMobile && isMobileMenuOpen)) && subMenuOpen && (
                <div className="sub-menu">
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('productLibrary', '产品库')}
                  >
                    <span className="sub-menu-icon">
                      <BsBoxSeam />
                    </span>
                    <span className="sub-menu-label">产品库</span>
                  </div>
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('resourceLibrary', '资源库')}
                  >
                    <span className="sub-menu-icon">
                      <MdStorage />
                    </span>
                    <span className="sub-menu-label">资源库</span>
                  </div>
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('processTemplateLibrary', '工艺库')}
                  >
                    <span className="sub-menu-icon">
                      <BsTools />
                    </span>
                    <span className="sub-menu-label">工艺库</span>
                  </div>
                </div>
              )}

              {/* 制造工艺规划菜单 */}
              <div 
                className={`sider-menu-item ${manufacturingSubMenuOpen ? 'active' : ''}`}
                onClick={() => (!collapsed || isMobile) && setManufacturingSubMenuOpen(!manufacturingSubMenuOpen)}
              >
                <span className="sider-menu-icon">
                  <AiOutlineTool />
                </span>
                <span className="sider-menu-label">制造工艺规划</span>
                {(!collapsed || isMobile && isMobileMenuOpen) && (
                  <span className="sider-menu-caret" onClick={toggleManufacturingSubMenu}>
                    {manufacturingSubMenuOpen ? <UpOutlined /> : <DownOutlined />}
                  </span>
                )}
              </div>

              {/* 制造工艺规划子菜单 */}
              {(!collapsed || (isMobile && isMobileMenuOpen)) && manufacturingSubMenuOpen && (
                <div className="sub-menu">
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('productBOM', '产品BOM')}
                  >
                    <span className="sub-menu-icon">
                      <BsFileEarmarkCode />
                    </span>
                    <span className="sub-menu-label">产品BOM</span>
                  </div>
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('productProcess', '产品工艺')}
                  >
                    <span className="sub-menu-icon">
                      <MdOutlineFactory />
                    </span>
                    <span className="sub-menu-label">产品工艺</span>
                  </div>
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('productBOP', '产品BOP')}
                  >
                    <span className="sub-menu-icon">
                      <BsFileEarmarkCode />
                    </span>
                    <span className="sub-menu-label">产品BOP</span>
                  </div>
                </div>
              )}

              {/* 系统设置菜单 */}
              <div 
                className={`sider-menu-item ${systemSettingsSubMenuOpen ? 'active' : ''}`}
                onClick={() => (!collapsed || isMobile) && setSystemSettingsSubMenuOpen(!systemSettingsSubMenuOpen)}
              >
                <span className="sider-menu-icon">
                  <FiSettings />
                </span>
                <span className="sider-menu-label">系统设置</span>
                {(!collapsed || isMobile && isMobileMenuOpen) && (
                  <span className="sider-menu-caret" onClick={toggleSystemSettingsSubMenu}>
                    {systemSettingsSubMenuOpen ? <UpOutlined /> : <DownOutlined />}
                  </span>
                )}
              </div>

              {/* 系统设置子菜单 */}
              {(!collapsed || (isMobile && isMobileMenuOpen)) && systemSettingsSubMenuOpen && (
                <div className="sub-menu">
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('intelligentRecommendation', '智能推荐', 'IntelligentRecommendation', { initialActiveTab: 'models' })}
                  >
                    <span className="sub-menu-icon">
                      <AiOutlineCodeSandbox />
                    </span>
                    <span className="sub-menu-label">智能推荐</span>
                  </div>
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('dataVersion', '数据版本')}
                  >
                    <span className="sub-menu-icon">
                      <AiOutlineDatabase />
                    </span>
                    <span className="sub-menu-label">数据版本</span>
                  </div>
                  <div 
                    className="sub-menu-item"
                    onClick={() => addTab('sampleData', '样例数据')}
                  >
                    <span className="sub-menu-icon">
                      <BsDatabaseFillGear />
                    </span>
                    <span className="sub-menu-label">样例数据</span>
                  </div>
                </div>
              )}
            </div>
            
            {!isMobile && (
              <div className="sider-actions">
                <Button 
                  type="text" 
                  icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                  onClick={handleCollapseClick}
                  className="sider-action-btn"
                  title={collapsed ? "展开菜单" : "收起菜单"}
                />
                {!collapsed && !isMobile && (
                  <Button 
                    type="text" 
                    icon={pinned ? <PushpinFilled /> : <PushpinOutlined />}
                    onClick={handlePinClick}
                    className={`sider-action-btn ${pinned ? 'pinned' : ''}`}
                    title={pinned ? "解除锁定" : "锁定菜单"}
                  />
                )}
              </div>
            )}
          </div>
          
          {/* 移动端菜单遮罩层 */}
          {isMobile && isMobileMenuOpen && (
            <div 
              className="mobile-menu-overlay"
              onClick={() => setIsMobileMenuOpen(false)}
            ></div>
          )}
          
          <div className={`layout-content ${isMobile ? 'mobile-content' : ''}`}>
            <div className="content-body">
              {renderTabContent(activeTab)}
            </div>
          </div>
        </div>
        
        <Footer className={`layout-copyright ${isMobile ? 'mobile-footer' : ''}`}>
          <div className="footer-content">
            <span>Copyright © 2025 GXT All Rights Reserved.</span>
            <span>国信科技 版权所有</span>
            <a 
              href="https://beian.miit.gov.cn/#/Integrated/index" 
              target="_blank" 
              rel="noreferrer"
              className="icp-link"
            >
              粤ICP备15086614号
            </a>
          </div>
        </Footer>
      </Layout>
    </div>
  )
}

// App根组件
function App() {
  return (
    <TabsProvider>
      <AppContent />
    </TabsProvider>
  );
}

export default App
